import {
  getRequestBody,
  isLogin,
  accountInfo,
  cleanToken,
} from '@/utils/Account'
import { createFetch } from '@vueuse/core'
import { isJson, setUrlParams } from 'lj-utils'
import { MessagePlugin } from 'tdesign-vue-next'
import { toPage } from '@/router'

export const baseUrl =
  'https://cloud1-3g8avjyo613a9ca1-1326935991.ap-shanghai.app.tcloudbase.com'
export const getReq = async (url, query = {}) => {
  try {
    const getUrl = url + setUrlParams({ ...query, ...getRequestBody() })
    const { data } = await useReq(getUrl)
    return data?.value
  } catch (error) {
    return Promise.reject(error)
  }
}
export const postReq = async (url, params = {}) => {
  try {
    const getUrl = url //+ setUrlParams(params)
    const res = await useReq(getUrl).post({
      ...getRequestBody(),
      ...params,
    })
    // if (res.statusCode !== 200) {
    //   return Promise.reject(res.data)
    // }
    return res?.data?.value
  } catch (error) {
    return Promise.reject(error)
  }
}

export const useReq = createFetch({
  baseUrl,
  combination: 'overwrite',
  options: {
    // beforeFetch in pre-configured instance will only run when the newly spawned instance do not pass beforeFetch
    beforeFetch({ options }) {
      console.log('beforeFetch')
      console.log(options)
      return { options }
    },
    afterFetch(ctx) {
      if (isJson(ctx.data)) {
        ctx.data = JSON.parse(ctx.data)
      }
      switch (ctx.data.code) {
        case 1:
          MessagePlugin.error({
            content: '参数异常',
          })
          break
        case 2:
          MessagePlugin.error({
            content: '登录已过期,请重新登录',
          })
          cleanToken()
          checkLogin()
          break
        case 3:
          MessagePlugin.error({
            content: '尚末登录，或已在其他网页登录，请重新登录',
          })
          cleanToken()
          checkLogin()
          break
      }
      console.log('afterFetch:::', ctx.data)

      return ctx
    },
  },
})
export default useReq

// 定义你想要在页面初始化时执行的方法
function checkLogin() {
  console.log('check login123', accountInfo)
  if (!isLogin()) {
    toPage('/login')
  }
}
